<template>
  <div class="sign-wrap">
    <div class="page-title-wrap">
      <button class="back-button" @click="handleBackToMenu">返回</button>
      <PageTitleWrap :pageTitle="pageTitle" />
      <div class="filter-button" @click="showPopup">
        {{ filterButtonText }}
      </div>
    </div>
    <div class="songList" :class="{ 'songList-empty': songOrderListLength === 0 }">
      <template v-if="songOrderListLength > 0">
        <div
          class="songItem"
          v-for="item in songOrderList"
          :key="item.heart_wall_id"
          :class="{
            wait: item.sort === 0 && currentSongOrderId !== item.heart_wall_id,
            end: item.sort === 1 && currentSongOrderId !== item.heart_wall_id,
            in: currentSongOrderId === item.heart_wall_id,
          }"
          @click="chooseTargetSongOrder(item)"
        >
          <div class="songLeft">
            <div class="deskNumBox" v-if="getDeskNum(item)" @click.stop="showSongInfo(item)">
              {{ getDeskNum(item) }}
            </div>
            <div class="songName">{{ item.title }}</div>
          </div>
          <div class="songStatus">
            <div>
              {{ statusFilter(item.sort, item.heart_wall_id) }}
            </div>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="no-song">暂无歌曲</div>
      </template>
    </div>
    <van-popup v-model="showDatePicker" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        title="选择起始时间"
        @confirm="onConfirm"
        @cancel="onCancel"
      />
    </van-popup>
    <div class="func-button-container" v-if="songOrderListLength > 0">
      <FuncButton
        @click="prevSongOrder"
        class="func-button"
      >
        上一首
      </FuncButton>
      <FuncButton
        @click="nextSongOrder"
        class="func-button"
      >
        下一首
      </FuncButton>
      <FuncButton
        @click="resetAllSongs"
        class="func-button"
      >
        全部重置
      </FuncButton>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import PageTitleWrap from '@/views/v2/components/PageTitle.vue';
import FuncButton from '@/views/v2/components/FuncButton.vue';
import { editMusicStatus, getMusicList } from '@/api/index';

export default {
  name: 'OrderSong',
  components: {
    PageTitleWrap,
    FuncButton,
  },
  data() {
    return {
      songOrderList: [],
      currentSongOrderId: undefined,
      pageTitle: '点歌',
      showDatePicker: false,
      currentDate: new Date(),
      startTime: null,
    };
  },
  computed: {
    ...mapState({
      currentSongId: (state) => state.currentSongId,
    }),
    filterButtonText() {
      return this.startTime ? this.startTime : '选择时间';
    },
    currentSongOrderIndex() {
      return this.songOrderList.findIndex((item) => item.heart_wall_id === this.currentSongOrderId);
    },
    songOrderListLength() {
      return this.songOrderList.length;
    },
  },
  created() {
    // 从 localStorage 恢复 startTime
    this.loadStartTimeFromStorage();
    this.initMusicList();
  },
  watch: {
    currentSongId: {
      handler(newVal) {
        if (newVal) {
          this.currentSongOrderId = newVal;
          editMusicStatus({
            heartWallId: this.currentSongOrderId,
            sort: 1,
          })
            .then(() => {
              this.requestMusicList(this.currentSongOrderId);
            })
            .catch((err) => {
              console.log(err);
            });
        }
      },
      immediate: true,
    },
  },
  methods: {
    getDeskNum(item) {
      try {
        if (!item || !item.photo_end_url) return '';
        const parsed = typeof item.photo_end_url === 'string' ? JSON.parse(item.photo_end_url) : item.photo_end_url;
        const num = parsed && (parsed.deskNum || parsed.desknum || parsed.desk_no);
        if (!num && num !== 0) return '';
        const txt = String(num).padStart(2, '0');
        return `${txt}桌`;
      } catch (e) {
        return '';
      }
    },
    showSongInfo(item) {
      let singerInfo = {};
      try {
        singerInfo = item.singerInfo ? JSON.parse(item.singerInfo) : {};
      } catch (error) {
        console.warn('解析 singerInfo 失败:', error, item.singerInfo);
        singerInfo = {};
      }

      let bless = '';
      try {
        const photoEnd = typeof item.photo_end_url === 'string' ? JSON.parse(item.photo_end_url) : item.photo_end_url;
        bless = (photoEnd && (photoEnd.blessing || photoEnd.bless || '')) || '';
      } catch (error) {
        console.warn('解析 photo_end_url 失败:', error, item.photo_end_url);
        bless = '';
      }

      this.$dialog.alert({
        title: '歌曲信息',
        message: `
          <div class="song-info-dialog">
            <div class="song-info-song-name">${item.title || ''}</div>
            <div class="song-info-section">
              <div class="song-info-title song-info-title--center">点歌人</div>
              <div class="song-info-row">
                <img src="${item.avator || ''}" alt="点歌人头像" class="song-info-avatar">
                <div class="song-info-text">
                  <p class="song-info-name">${item.wx_name || '匿名'}</p>
                  <p class="song-info-desc">${this.formatDateTime(item.create_time)}</p>
                </div>
              </div>
            </div>
            <div class="song-info-section">
              <div class="song-info-title song-info-title--center">歌手</div>
              <div class="song-info-row">
                <img src="${singerInfo.avator || ''}" alt="歌手头像" class="song-info-avatar">
                <div class="song-info-text song-info-text--center">
                  <p class="song-info-name">${singerInfo.name || '未知歌手'}</p>
                  <p class="song-info-desc"></p>
                </div>
              </div>
            </div>
            ${
  bless
    ? `<div class="song-info-section song-info-bless">
                    <div class="song-info-title song-info-title--center">祝福语</div>
                    <div class="song-info-row song-info-row--center">
                      <div class="song-info-text song-info-text--center">
                        <p class="song-info-bless-text">${bless}</p>
                      </div>
                    </div>
                  </div>`
    : ''
}
          </div>
        `,
        allowHtml: true,
      });
    },
    formatDateTime(value) {
      if (!value) return '';
      const date = new Date(value);
      if (Number.isNaN(date.getTime())) return value;
      const Y = date.getFullYear();
      const M = (date.getMonth() + 1).toString().padStart(2, '0');
      const D = date.getDate().toString().padStart(2, '0');
      const h = date.getHours().toString().padStart(2, '0');
      const m = date.getMinutes().toString().padStart(2, '0');
      const s = date.getSeconds().toString().padStart(2, '0');
      return `${Y}/${M}/${D} ${h}:${m}:${s}`;
    },
    showPopup() {
      this.showDatePicker = true;
    },
    onConfirm(value) {
      const d = new Date(value);
      this.startTime = `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d
        .getDate()
        .toString()
        .padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d
        .getMinutes()
        .toString()
        .padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}`;
      // 保存 startTime 到 localStorage
      this.saveStartTimeToStorage();
      this.showDatePicker = false;
      this.initMusicList();
    },
    onCancel() {
      this.showDatePicker = false;
    },
    initMusicList() {
      getMusicList({ startTime: this.startTime })
        .then((res) => {
          console.log('initMusicList -> getMusicList 响应:', res);
          this.songOrderList = res.data.list || [];
          // 查找第一个 sort === 0 的音乐
          const firstWaitSong = this.songOrderList.find((item) => item.sort === 0);
          if (firstWaitSong) {
            this.currentSongOrderId = firstWaitSong.heart_wall_id;
            this.updateData(this.currentSongOrderId, this.startTime);
          } else {
            this.currentSongOrderId = undefined;
            this.updateData('noneId', this.startTime);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleBackToMenu() {
      this.$emit('back-to-menu');
    },
    prevSongOrder() {
      let startIndex;
      if (this.currentSongOrderIndex === -1) {
        // 没有当前歌曲在唱，从列表末尾开始查找
        startIndex = this.songOrderListLength - 1;
      } else {
        // 从当前位置的前一个位置开始查找
        startIndex = this.currentSongOrderIndex - 1;
        if (startIndex < 0) {
          startIndex = this.songOrderListLength - 1; // 循环到末尾
        }
      }

      // 循环向前查找第一个待唱歌曲
      let foundIndex = -1;
      let checkedCount = 0;
      let currentCheckIndex = startIndex;

      while (checkedCount < this.songOrderListLength) {
        if (this.songOrderList[currentCheckIndex].sort === 0) {
          foundIndex = currentCheckIndex;
          break;
        }
        currentCheckIndex--;
        if (currentCheckIndex < 0) {
          currentCheckIndex = this.songOrderListLength - 1; // 循环到末尾
        }
        checkedCount++;
      }

      // 如果没找到待唱歌曲
      if (foundIndex === -1) {
        this.$toast('没有待唱歌曲了');
        return;
      }

      // 代码走到这里说明：有待唱歌曲
      const targetSongHeartWallId = this.songOrderList[foundIndex]?.heart_wall_id;

      // 只有当存在一首"进行中"的歌曲时，才需要将它标记为"已唱"
      if (this.currentSongOrderIndex !== -1) {
        editMusicStatus({
          heartWallId: this.songOrderList[this.currentSongOrderIndex].heart_wall_id,
          sort: 1,
        })
          .then(() => {
            this.requestMusicList(targetSongHeartWallId);
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        // 如果当前没有歌曲在播放
        this.requestMusicList(targetSongHeartWallId);
      }
    },
    chooseTargetSongOrder(targetSongOrder) {
      if (targetSongOrder.heart_wall_id === this.currentSongOrderId) {
        return;
      }
      if (targetSongOrder.sort === 1) {
        this.$dialog
          .confirm({
            title: '提示',
            message: '是否重置该歌曲状态为待唱?',
          })
          .then(() => {
            editMusicStatus({
              heartWallId: targetSongOrder.heart_wall_id,
              sort: 0,
            })
              .then(() => {
                this.requestMusicList();
              })
              .catch((err) => {
                console.log(err);
              });
          })
          .catch(() => {});
      } else {
        editMusicStatus({
          heartWallId: this.currentSongOrderId,
          sort: 1,
        })
          .then(() => {
            this.requestMusicList(targetSongOrder.heart_wall_id);
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    nextSongOrder() {
      let startIndex;
      if (this.currentSongOrderIndex === -1) {
        // 没有当前歌曲在唱，从列表开头开始查找
        startIndex = 0;
      } else {
        // 从当前位置的后一个位置开始查找
        startIndex = this.currentSongOrderIndex + 1;
        if (startIndex >= this.songOrderListLength) {
          startIndex = 0; // 循环到开头
        }
      }

      // 循环向后查找第一个待唱歌曲
      let foundIndex = -1;
      let checkedCount = 0;
      let currentCheckIndex = startIndex;

      while (checkedCount < this.songOrderListLength) {
        if (this.songOrderList[currentCheckIndex].sort === 0) {
          foundIndex = currentCheckIndex;
          break;
        }
        currentCheckIndex++;
        if (currentCheckIndex >= this.songOrderListLength) {
          currentCheckIndex = 0; // 循环到开头
        }
        checkedCount++;
      }

      // 如果没找到待唱歌曲
      if (foundIndex === -1) {
        // 进入此if说明歌曲全部已唱
        this.$toast('没有待唱歌曲了');
        return;
      }

      // 代码走到这里说明：有待唱歌曲

      // 获取下一首目标歌曲的ID
      const targetSongHeartWallId = this.songOrderList[foundIndex]?.heart_wall_id;

      // 只有当存在一首“进行中”的歌曲时，才需要将它标记为“已唱”
      if (this.currentSongOrderIndex !== -1) {
        // 先将当前歌曲状态更新为"已唱"
        editMusicStatus({
          heartWallId: this.songOrderList[this.currentSongOrderIndex].heart_wall_id,
          sort: 1,
        })
          .then(() => {
            // 成功后再请求列表，并将下一首设置为“进行中”
            this.requestMusicList(targetSongHeartWallId);
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        // 如果当前没有歌曲在播放 (currentSongOrderIndex === -1)
        // 直接请求列表，并将找到的第一首待唱歌曲设置为“进行中”
        this.requestMusicList(targetSongHeartWallId);
      }
    },
    statusFilter(status, id) {
      if (id === this.currentSongOrderId) {
        return '进行中';
      }
      if (status === 0) {
        return '待唱';
      }
      if (status === 1) {
        return '已唱';
      }
      return '其他状态';
    },
    requestMusicList(targetHeartWallId) {
      getMusicList({ startTime: this.startTime })
        .then((res) => {
          console.log('requestMusicList -> getMusicList 响应:', res);
          this.songOrderList = res.data.list || [];
          // 打印歌曲列表
          console.log('歌曲列表:', this.songOrderList);
          if (targetHeartWallId && targetHeartWallId !== this.currentSongOrderId) {
            // 通过 heart_wall_id 查找目标歌曲，避免使用可能过时的索引
            const targetSong = this.songOrderList.find((item) => item.heart_wall_id === targetHeartWallId);
            if (targetSong) {
              this.currentSongOrderId = targetSong.heart_wall_id;
              this.updateData(this.currentSongOrderId, this.startTime);
            } else {
              this.currentSongOrderId = undefined;
              this.updateData('noneId', this.startTime);
            }
          } else if (!targetHeartWallId) {
            // 如果没有目标歌曲ID，并且列表不为空，则默认选中第一首待唱歌曲
            const firstWaitSong = this.songOrderList.find((item) => item.sort === 0);
            if (firstWaitSong) {
              this.currentSongOrderId = firstWaitSong.heart_wall_id;
              this.updateData(this.currentSongOrderId, this.startTime);
            } else {
              this.currentSongOrderId = undefined;
              this.updateData('noneId', this.startTime);
            }
          } else {
            this.currentSongOrderId = undefined;
            this.updateData('noneId', this.startTime);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    async updateData(param, startTime) {
      if (this.$toast && this.$toast.loading) {
        this.$toast.loading({
          message: '加载中...',
          duration: 0,
        });
      }
      let finalParam = param;
      if (startTime) {
        finalParam = `${param},${startTime}`;
      }
      await this.$store.dispatch('instructions/sendInstruction', {
        type: 'game_control',
        action: 'orderSongUpdate',
        param: finalParam,
      });
      if (this.$toast && this.$toast.clear) {
        this.$toast.clear();
      }
    },
    resetAllSongs() {
      const sungSongs = this.songOrderList.filter((song) => song.sort === 1);
      if (sungSongs.length === 0) {
        this.$toast('没有已唱的歌曲');
        return;
      }
      this.$dialog
        .confirm({
          title: '提示',
          message: '确定要重置所有歌曲为待唱状态吗?',
        })
        .then(async () => {
          if (this.$toast && this.$toast.loading) {
            this.$toast.loading({
              message: '重置中...',
              duration: 0,
            });
          }
          try {
            // 串行执行，避免并发问题
            await sungSongs.reduce(async (previousPromise, song) => {
              await previousPromise;
              return editMusicStatus({
                heartWallId: song.heart_wall_id,
                sort: 0,
              });
            }, Promise.resolve());
            // 如果当前有正在播放的歌曲，也一并重置
            if (this.currentSongOrderId) {
              const currentPlayingSong = this.songOrderList.find((s) => s.heart_wall_id === this.currentSongOrderId);
              // 检查当前歌曲是否已在上面循环中被重置
              if (currentPlayingSong && currentPlayingSong.sort !== 1) {
                await editMusicStatus({
                  heartWallId: this.currentSongOrderId,
                  sort: 0,
                });
              }
            }
            this.$toast.success('重置成功');
            this.requestMusicList();
          } catch (error) {
            console.error('Failed to reset all songs:', error);
            this.$toast.fail('重置失败');
          } finally {
            if (this.$toast && this.$toast.clear) {
              this.$toast.clear();
            }
          }
        })
        .catch(() => {});
    },
    loadStartTimeFromStorage() {
      try {
        const savedStartTime = localStorage.getItem('orderSong_startTime');
        if (savedStartTime) {
          this.startTime = savedStartTime;
        }
      } catch (error) {
        console.warn('Failed to load startTime from localStorage:', error);
      }
    },
    saveStartTimeToStorage() {
      try {
        if (this.startTime) {
          localStorage.setItem('orderSong_startTime', this.startTime);
        } else {
          localStorage.removeItem('orderSong_startTime');
        }
      } catch (error) {
        console.warn('Failed to save startTime to localStorage:', error);
      }
    },
  },
};
</script>

<style>
.song-info-dialog {
  text-align: left;
  display: flex;
  flex-direction: column;
  gap: 18px;
  font-size: 18px;
  color: #1f2a44;
}
.song-info-song-name {
  font-size: 32px;
  font-weight: 700;
  text-align: center;
  color: #202f5a;
  margin: 4px 0;
}
.song-info-section {
  background: rgba(76, 121, 255, 0.05);
  border-radius: 3px;
  border: 1px solid rgba(76, 121, 255, 0.1);
  display: flex;
  flex-direction: column;
  padding: 8px 10px;
}
.song-info-title {
  font-size: 32px;
  font-weight: 600;
  color: #27355a;
  margin: 0;
  line-height: 1.05;
  padding: 2px 0;
}
.song-info-title--center {
  text-align: center;
}
.song-info-row {
  display: flex;
  align-items: stretch;
  gap: 3px;
  padding: 8px 0 6px;
  flex: 1;
}
.song-info-avatar {
  width: 72px;
  height: 72px;
  border-radius: 50%;
  object-fit: cover;
  background: #ffffff;
  border: 1px solid rgba(76, 121, 255, 0.2);
  flex-shrink: 0;
}
.song-info-text {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
  flex: 1;
  min-height: 72px;
}
.song-info-text--center {
  justify-content: center;
}
.song-info-text p {
  margin: 0;
}
.song-info-name {
  font-size: 32px;
  font-weight: 600;
  color: #27355a;
  line-height: 1.05;
}
.song-info-desc {
  font-size: 24px;
  color: #4a5370;
  line-height: 1.05;
}
.song-info-row--center {
  justify-content: center;
}
.song-info-bless-text {
  font-size: 32px;
  line-height: 1;
  color: #1f2a55;
  white-space: pre-wrap;
  margin: 0;
  text-align: center;
}
.van-dialog__message.van-dialog__message--has-title {
  padding-top: 0;
  padding-bottom: 0;
}
</style>
<style scoped>
.sign-wrap {
  height: 100%;
}
.page-title-wrap {
  position: relative;
  margin-bottom: 40px;
}
.filter-button {
  position: absolute;
  right: 0px;
  top: 64px;
  transform: translateY(-50%);
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.4);
  border-radius: 26px;
  color: #ffffff;
  font-size: 24px;
  padding: 6px 14px;
  backdrop-filter: blur(4px);
}
.back-button {
  position: absolute;
  left: 32px;
  top: 64px;
  transform: translateY(-50%);
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.4);
  border-radius: 26px;
  color: #ffffff;
  font-size: 28px;
  padding: 12px 32px;
  backdrop-filter: blur(4px);
}
.back-button:active {
  opacity: 0.8;
}
.func-button-container {
  display: flex;
  margin-top: 39px;
  justify-content: center;
  margin-top: 5.2vw;
  flex-wrap: wrap;
  align-items: center;
  row-gap: 4vw;
  column-gap: 4vw;
  padding: 0 4vw;
}
.songList {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  height: 80vh;
  overflow-y: scroll;
}
.songList-empty {
  height: 100px;
  justify-content: center;
}
.no-song {
  font-size: 36px;
  color: #333333;
}
.songItem {
  flex-shrink: 0;
  border-radius: 20px;
  display: flex;
  justify-content: space-between;
  width: 686px;
  height: 100px;
  padding: 0 32px;
  align-items: center;
}
.songLeft {
  display: flex;
  align-items: center;
  flex: 1;
  overflow: hidden;
}
.deskNumBox {
  width: 162px;
  height: 76px;
  border-radius: 15px;
  color: #ffffff;
  font-size: 34px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  border: 1px solid rgba(255, 255, 255, 0.6);
  margin-right: 20px; /* 与歌曲名字距离 */
}
.songName {
  font-size: 32px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.songStatus {
  font-size: 32px;
}
.songItem.wait {
  background: #3A62D0;
}
.songItem.wait .songName {
  color: #ece9ff;
}
.songItem.wait .songStatus {
  color: #ffffff;
}
.songItem.in {
  background-color: #ffffff;
}
.songItem.in .songName {
  color: #333333;
}
.songItem.in .songStatus {
  color: #fb5aa7;
}
.songItem.in .deskNumBox {
  background: #4c79ff;
  border: none;
  color: #ffffff;
}
.songItem.end {
  background-color: #8A90A8;
}
.songItem.end .songName {
  color: #ece9ff;
}
.songItem.end .songStatus {
  color: #ffffff;
}
</style>
